/**
  *@File文件:BillService.java
  *@Date日期:2017年7月17日 上午9:42:16
  *@Copyright版权:Corporation 2017
  */
package com.qiaomengapp.serviceImp;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qiaomengapp.bean.Bill;
import com.qiaomengapp.bean.BillAndBillGood;
import com.qiaomengapp.bean.BillAndBillGoodWrapper;
import com.qiaomengapp.bean.BillDetailMessage;
import com.qiaomengapp.bean.BillGood;
import com.qiaomengapp.bean.Card;
import com.qiaomengapp.bean.CommissionDetail;
import com.qiaomengapp.bean.DistributionBill;
import com.qiaomengapp.bean.Platform;
import com.qiaomengapp.bean.Provider;
import com.qiaomengapp.bean.ShopBill;
import com.qiaomengapp.bean.ShopGoodWrap;
import com.qiaomengapp.bean.UserRecord;
import com.qiaomengapp.dao.BillGoodMapper;
import com.qiaomengapp.dao.BillMapper;
import com.qiaomengapp.dao.CardMapper;
import com.qiaomengapp.dao.CommissionDetailMapper;
import com.qiaomengapp.dao.DistributionBillMapper;
import com.qiaomengapp.dao.PlatformMapper;
import com.qiaomengapp.dao.ProviderMapper;
import com.qiaomengapp.dao.ShopBillMapper;
import com.qiaomengapp.dao.ShopGoodMapper;
import com.qiaomengapp.dao.ShopMapper;
import com.qiaomengapp.dao.UserRecordMapper;
import com.qiaomengapp.exception.CustomException;
import com.qiaomengapp.service.IBillManageService;
import com.qiaomengapp.util.CommUtils;

/**
 * @Description描述: 订单逻辑处理类
 * @Author作者 wangzongwen
 * @Date日期:2017年7月17日
 */
/**
 * @Description描述:
 * @Author作者 wangzongwen
 * @Date日期:2017年7月17日
 */
@Service
public class ImpBillManageService implements IBillManageService {
	// 操作订单数据表
	@Autowired
	private BillMapper billMapper;

	// 操作订单商品表
	@Autowired
	private ShopGoodMapper shopGoodMapper;

	// 操作订单商品表
	@Autowired
	private BillGoodMapper billGoodMapper;

	// 商家订单
	@Autowired
	private DistributionBillMapper distributionBillMapper;

	// 操作银行卡表
	@Autowired
	private CardMapper cardMapper;

	// 用户资金变动记录
	@Autowired
	private UserRecordMapper userRecordMapper;

	// 操作平台表
	@Autowired
	private PlatformMapper platformMapper;

	// 商铺表
	@Autowired
	private ShopMapper shopMapper;

	// 操作佣金记录表
	@Autowired
	private CommissionDetailMapper commissionDetailMapper;

	// 操作供应商表
	@Autowired
	private ProviderMapper providerMapper;

	// 操作商铺信息表
	@Autowired
	private ShopBillMapper shopBillMapper;

	/**
	 * @Description描述: 创建订单
	 * @param billAndBillGoodWrappers
	 *            订单和订单商品的包装类数组
	 * @throws CustomException
	 * @return void
	 */
	public void insertBill(BillAndBillGoodWrapper billAndBillGoodWrapper) throws CustomException {
		if (billAndBillGoodWrapper == null) {
			return;
		}
		List<BillAndBillGood> billAndBillGoods = billAndBillGoodWrapper.getBillAndBillGoods();
		// 每一个订单和订单商品包装类创建一个订单
		for (BillAndBillGood billAndBillGood : billAndBillGoods) {
			Bill bill = billAndBillGood.getBill();
			// 添加订单状态
			bill.setStatus(1);
			// 创建订单编号
			bill.setBillCode(CommUtils.getUpperCaseUuid().substring(0, 16));
			bill.setCreateTime(new Date());
			// 得到订单中的商品
			List<BillGood> billGoods = billAndBillGood.getBillGoods();
			// 遍历求出订单总价格
			double sum = 0;
			for (BillGood billGood : billGoods) {
				billGood.setBillCode(bill.getBillCode());
				sum += billGood.getPrice() * billGood.getNum();
			}
			bill.setPrice(sum);
			// 创建订单
			int i = billMapper.insertBill(bill);
			if (i == 0) {
				throw new CustomException("订单创建失败！");
			}
			// 添加订单商品
			int j = billGoodMapper.insertBillGood(billGoods);
			if (j == 0) {
				throw new CustomException("订单商品添加失败");
			}
			// 添加商家订单
			DistributionBill distributionBill = new DistributionBill();
			distributionBill.setBillCode(bill.getBillCode());
			distributionBill.setMoney(bill.getPrice());
			distributionBill.setStatus(1);
			distributionBill.setShopId(bill.getShopId());

			int k = distributionBillMapper.insertDistributionBill(distributionBill);
			if (k == 0) {
				throw new CustomException("商家订单创建失败");
			}
		}
	}

	/**
	 * @Description描述: 订单付款
	 * @param userId
	 *            付款的用户id
	 * @param billCode
	 *            订单编号
	 * @param cardCode
	 *            银行卡编号
	 * @throws CustomException
	 * @return void
	 */
	public void updatePayment(int userId, String billCode, long cardCode) throws CustomException {
		// 根据订单编号查询订单
		Bill bill = billMapper.selectBillByCode(billCode);
		if (bill == null) {
			throw new CustomException("该订单不存在");
		}
		if (bill.getStatus() != 1) {
			throw new CustomException("该订单不能进行付款");
		}
		// 改变订单状态
		updateBillStatus(2, billCode);
		// 根据订单编号查询订单商品和订单
		List<BillGood> billGoods = billGoodMapper.selectBillGood(billCode);
		for (BillGood billGood : billGoods) {
			// 修改商品销量
			int j = shopGoodMapper.update_shopGoodSalesCount(billGood.getNum(), billGood.getShopGoodId());
			if ( j == 0) {
				throw new CustomException("商品数量修改失败！");
			}
		}

		// 修改用户银行卡余额
		Card card = new Card();
		card.setCardCode(cardCode);
		int i = cardMapper.update_payMoney(card, bill.getPrice());
		if (i == 0) {
			throw new CustomException("银行账号余额不足，请更换支付方式！");
		}

		// 添加一条资金变动记录
		UserRecord userRecord = new UserRecord();
		userRecord.setUserId(userId);
		userRecord.setType(1);
		userRecord.setMoney(bill.getPrice());
		userRecord.setCreateTime(new Date());
		int j = userRecordMapper.insert_userRecord(userRecord);
		if (j == 0) {
			throw new CustomException("支付失败！");
		}

		// 用户支付的金额转入平台
		Platform platform = new Platform();
		platform.setMoney(bill.getPrice());
		platform.setUserId(userId);
		platform.setBillCode(billCode);
		platform.setCardCode(cardCode);
		int k = platformMapper.insertPlatform(platform);
		if (k == 0) {
			throw new CustomException("支付失败！");
		}
	}

	/**
	 * @Description描述: 用户收货
	 * @param billCode
	 *            订单编号
	 * @return void
	 * @throws CustomException
	 */
	public void updateAcceptBillGood(String billCode) throws CustomException {
		// 根据订单编号查询订单
		Bill bill = billMapper.selectBillByCode(billCode);
		if (bill == null) {
			throw new CustomException("该订单不存在");
		}
		if (bill.getStatus() != 2) {
			throw new CustomException("该订单不能进行收货");
		}
		updateBillStatus(3, billCode);
	}

	/**
	 * @Description描述: 订单完成
	 * @param billCode
	 *            完成的订单编号
	 * @throws CustomException
	 * @return void
	 */
	public void updateBillComplete(String billCode) throws CustomException {
		// 根据订单编号查询订单
		Bill bill = billMapper.selectBillByCode(billCode);
		if (bill == null) {
			throw new CustomException("该订单不存在！");
		}

		if (bill.getStatus() != 3) {
			throw new CustomException("该订单还不能完成！");
		}
		// 更改订单状态
		updateBillStatus(4, billCode);
		// 根据订单编号查询订单商品
		List<BillGood> billGoods = billGoodMapper.selectBillGood(billCode);
		// 保存总总佣金
		double commissionSum = 0;
		for (BillGood billGood : billGoods) {
			// 得到商铺商品id
			ShopGoodWrap shopGoodWrap = shopGoodMapper.select_ShopGoodWrap(billGood.getShopGoodId());
			// 累加商品佣金
			commissionSum += shopGoodWrap.getCommission() * billGood.getNum();
		}
		// 从平台拿出用户支付的资金
		int i = platformMapper.updatePlatformMoney(billCode, commissionSum);
		// 修改商铺总佣金和可用佣金
		int j = shopMapper.update_able_addCommission(commissionSum, bill.getShopId());
		int l = shopMapper.update_sum_addCommission(commissionSum, bill.getShopId());
		// 增加一条商铺佣金记录
		CommissionDetail commissionDetail = new CommissionDetail();
		commissionDetail.setType(1);
		commissionDetail.setMoney(commissionSum);
		commissionDetail.setCreatetime(new Date());
		commissionDetail.setShopId(bill.getShopId());
		// 根据商铺id得到商铺可用佣金
		double able_commission = shopMapper.select_able_commission(bill.getShopId());
		commissionDetail.setBalance(able_commission);
		int k = commissionDetailMapper.insertCommissionDetail(commissionDetail);
		if (i == 0 || j == 0 || l == 0 || k == 0) {
			throw new CustomException("订单完成失败！");
		}
		// 通过订单编号查询供应商
		Provider provider = billMapper.selectProviderByBillCode(billCode);
		// 剩余资金交给供货商(供应商得到的钱为订单价格减去总佣金)
		int m = platformMapper.updatePlatformMoney(billCode, bill.getPrice() - commissionSum);
		int n = providerMapper.updateProviderBalance(provider.getId(), bill.getPrice() - commissionSum);
		if (m == 0 || n == 0) {
			throw new CustomException("订单完成失败！");
		}
		// 向商铺发送订单完成信息
		ShopBill shopBill = new ShopBill();
		shopBill.setBillCode(billCode);
		shopBill.setRealMoney(commissionSum);
		shopBill.setShopId(bill.getShopId());
		shopBill.setType(1);
		shopBill.setCreateTime(new Date());

		int o = shopBillMapper.insertShopBill(shopBill);
		if (o == 0) {
			throw new CustomException("订单完成信息发送失败！");
		}
	}

	/**
	 * @Description描述: 用户退款订单
	 * @param billCode
	 *            订单编号
	 * @return void
	 * @throws CustomException
	 */
	public void updateBillRefund(String billCode) throws CustomException {
		// 根据订单编号查询订单
		Bill bill = billMapper.selectBillByCode(billCode);
		if (bill == null) {
			throw new CustomException("退款的订单不存在");
		}
		if (bill.getStatus() != 3) {
			throw new CustomException("该订单不能进行退款");
		}
		// 修改订单状态
		updateBillStatus(5, billCode);
		// 根据订单编号查询平台记录
		Platform platform = platformMapper.selectPlatformByBillCode(billCode);
		if (platform.getMoney() == 0) {
			throw new CustomException("该订单不能进行退款");
		}
		// 平台进行退款
		int i = platformMapper.updatePlatformMoney(billCode, platform.getMoney());
		Card card = new Card();
		card.setCardCode(platform.getCardCode());
		int j = cardMapper.update_chargeMoney(card, platform.getMoney());
		// 添加一条用户资金变动记录
		UserRecord userRecord = new UserRecord();
		userRecord.setUserId(platform.getUserId());
		userRecord.setType(2);
		userRecord.setMoney(platform.getMoney());
		userRecord.setCreateTime(new Date());
		int k = userRecordMapper.insert_userRecord(userRecord);
		if (i == 0 || j == 0 || k == 0) {
			throw new CustomException("退款失败！");
		}
		// 更改商品销量和库存
		List<BillGood> billGoods = billGoodMapper.selectBillGood(billCode);
		for (BillGood billGood : billGoods) {
			// 修改商品销量
			int m = shopGoodMapper.update_shopGoodSalesCount(-(billGood.getNum()), billGood.getShopGoodId());
			if ( m == 0) {
				throw new CustomException("退款失败！");
			}
		}
	}

	/**
	 * @Description描述: 改变用户订单和商家订单的状态
	 * @param status
	 *            要改变的状态
	 * @return void
	 * @throws CustomException
	 */
	private void updateBillStatus(int status, String billCode) throws CustomException {
		int i = billMapper.updateBillStatus(status, billCode);
		int j = distributionBillMapper.updateDistributionBillStatus(status, billCode);
		if (i == 0 && j == 0) {
			throw new CustomException("订单状态改变失败！");
		}
	}

	@Override
	public List<Bill> selectBillByStatus(Integer status,int userId) {
		List<Bill> list = billMapper.selectBillByStatus(status,userId);
		return list;
	}

	@Override
	public List<BillDetailMessage> selectBillDetailByBillCode(String billCode) {
		List<BillDetailMessage> list = billMapper.selectBillDetailByBillCode(billCode);
		return list;
	}

	@Override
	public List<BillDetailMessage> selectDistributionBillByBillCode(String billCode) {
		List<BillDetailMessage> list = billMapper.selectDistributionBillByBillCode(billCode);
		return list;
	}

	@Override
	public Provider selectProviderByBillCode(String billCode) {
		
		Provider provider = billMapper.selectProviderByBillCode(billCode);
		
		return provider;
	}

	@Override
	public Bill selectBillByCode(String billCode) {
		Bill bill = billMapper.selectBillByCode(billCode);
		return bill;
	}
}
